package com.myGisChannel.controller;

import java.util.List;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.geotools.geometry.jts.*;
import org.json.JSONArray;
import org.json.JSONObject;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.mvc.multiaction.MultiActionController;

import com.myGis.entities.Layer;
import com.myGis.entities.SimpleField;
import com.myGis.entities.SpatialObject;
import com.myGis.entities.ValueField;
import com.myGis.services.IMyGisServices;
import com.myGis.services.MyGisServer;
import com.vividsolutions.jts.geom.GeometryFactory;
import com.vividsolutions.jts.geom.LineString;
import com.vividsolutions.jts.geom.MultiLineString;
import com.vividsolutions.jts.geom.MultiPoint;
import com.vividsolutions.jts.geom.MultiPolygon;
import com.vividsolutions.jts.geom.Point;
import com.vividsolutions.jts.geom.Polygon;
import com.vividsolutions.jts.io.WKTReader;

public class AddLayerInfoController extends MultiActionController{
	
	static String LAYER_TO_WORK = "layerToWork";
	
	public ModelAndView addSpatialObject(HttpServletRequest request, HttpServletResponse response) throws Exception{
		ModelAndView mav = new ModelAndView("/layersPages/addSpatialInfoAjaxRs");
		String feature = (String) request.getParameter("featureToSend");
 		String jSonSimlpeValue = (String) request.getParameter("jSonSimlpeValue");
 		Layer layer = (Layer) request.getSession().getAttribute(LAYER_TO_WORK);
 		
 		/*if(true){
		return mav;
 		}*/
 		// Se crea el SPATIAL_OBJECT
 		SpatialObject so = new SpatialObject();
		
 		//TODO lo que sigue deberia ser un factory, el objetivo seria pasarle el tipo de geometria a que no devueva el 
		// objeto que se corresponda, en este caso para probar estamos usando un POINT
		GeometryFactory geometryFactory = (GeometryFactory) JTSFactoryFinder.getGeometryFactory( null );
	 	
		WKTReader reader = new WKTReader(geometryFactory);
		

		if(feature.contains("LINESTRING")){
	 		LineString lineString = (LineString) reader.read(feature);
	 		lineString.setSRID(22195);
	 		
	 		LineString vector[] = new LineString[1];
		 	vector[0]=lineString;
		 	
		 	MultiLineString	ml = new MultiLineString(vector, geometryFactory);
		 	ml.setSRID(22195);
		 	so.setGeometry(ml);
	 	}else if(feature.contains("POINT")){
	 		Point point = (Point) reader.read(feature);
		 	point.setSRID(22195);
		 	
		 	Point vector[] = new Point[1];
		 	vector[0]=point;
		 	
		 	MultiPoint mp = new MultiPoint(vector, geometryFactory);
		 	mp.setSRID(22195);
		 	so.setGeometry(mp);
	 	}else if(feature.contains("POLYGON")){
	 		Polygon polygon = (Polygon) reader.read(feature);
	 		polygon.setSRID(22195);
	 		
	 		Polygon vector[] = new Polygon[1];
	 		vector[0] = polygon;
	 		
	 		MultiPolygon mp = new MultiPolygon(vector, geometryFactory);
	 		mp.setSRID(22195);
		 	so.setGeometry(mp);
	 	}
		
		
		so.setLayer(layer);
	 		
	 	IMyGisServices mgs = MyGisServer.getInstance();
	 		
	 	mgs.save(so);
	 	
		layer.getSpatialObject().add(so);
		
		layer.getSpatialObject().add(so);
 		
 		// Se prepara todo para crear el VALUE_FIELD
 		JSONArray jso = new JSONArray(jSonSimlpeValue);
 		for (int i = 0; i < jso.length(); i++) {
 			SimpleField sf = getSimpleFielByName(layer.getSimpleFields(), (String)((JSONObject)jso.get(i)).get("id"));
 			ValueField vf = new ValueField();
 				vf.setSimpleField(sf);
 				vf.setSpatialObject(so);
 				vf.setValue((String)((JSONObject)jso.get(i)).get("valor"));
 				mgs.save(vf);
 				sf.getValueFields().add(vf);
 				mgs.update(sf);
		}

		mav.addObject("test", "af");
		return mav;
		
	}

	private SimpleField getSimpleFielByName(List<SimpleField> simpleFields,	String key) {
		
		for(SimpleField sf: simpleFields){
			if(key.equals(sf.getName())){
				return sf;
			}
		}
		return null;
	}
	
	public ModelAndView modifySpatialObject(HttpServletRequest request, HttpServletResponse response) throws Exception{
		ModelAndView mav = new ModelAndView("/layersPages/addSpatialInfoAjaxRs");
		String feature = (String) request.getParameter("featureToSend");
 		String jSonSimlpeValue = (String) request.getParameter("jSonSimlpeValue");
 		Layer layer = (Layer) request.getSession().getAttribute(LAYER_TO_WORK);

 		JSONArray jsa = new JSONArray(jSonSimlpeValue);
 		//IMyGisFinderServices imgfs = MyGisFinderServices.getInstance();
 		IMyGisServices imgs = MyGisServer.getInstance();
 		for(int i = 0; i < jsa.length();i++){
 			JSONObject json = (JSONObject)jsa.get(i);
 			if(!json.get("newValueInToFront").equals(json.get("valueInToServer"))){
 				String id = (String)json.get("valueFieldInToServer");
 				ValueField vf = imgs.findValueFieldById(new Long(id));
 				vf.setValue((String)json.get("newValueInToFront"));
 				imgs.update(vf);
 			}
 		}
 		
 		return mav;
		
	}
}
